package me.daei.soundmeter;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.Date;

import me.daei.soundmeter.mail.Mail;
import me.daei.soundmeter.widget.SoundDiscView;

public class MainActivity extends ActionBarActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {

    float volume = 10000;
    private SoundDiscView soundDiscView;
    private MyMediaRecorder mRecorder;
    private static final int msgWhat = 0x1001;
    private static final int refreshTime = 100;
    private Date lastDate = new Date();
    private static boolean activeStats = false;
    PowerManager.WakeLock wakeLock = null;
    private String to_1 = "466419709@qq.com";
    private String to_2 = "1970594996@qq.com";
    private static boolean isListen = false;
    private static int[] setting = {};
    private static int[] setting_low = {80,90,100};
    private static int[] setting_normal = {70,80,90};
    private static int[] setting_Higth = {60,70,80};

    private static int[] padding ={};
    private static int[] padding_Higth = {30,15,6};
    private static int[] padding_normal = {15,7,2};
    private static int[] padding_low= {5,3,1};
    @SuppressLint("InvalidWakeLockTag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecorder = new MyMediaRecorder();

        activeStats = true;
        isListen = true;
        setting = setting_normal;
        padding = padding_normal;

        Button btnClick = (Button) findViewById(R.id.btn_test);//控件的获取
        btnClick.setOnClickListener(this);
        Switch swit = (Switch) findViewById(R.id.swh_listen);
        swit.setOnClickListener(this);

        EditText text = (EditText) findViewById(R.id.email);
        text.setText(to_1);

        Spinner sp_setting = (Spinner) findViewById(R.id.spinner_setting);
        sp_setting.setSelection(1);
        sp_setting.setOnItemSelectedListener(this);

        Spinner sp_padding = (Spinner) findViewById(R.id.spinner_padding);
        sp_padding.setSelection(1);
        sp_padding.setOnItemSelectedListener(this);

        //息屏正常运行
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
        wakeLock.acquire();

    }

    Handler handler_2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("value");
            Log.i("mylog", "请求结果为-->" + val);
            // TODO
            // UI界面的更新等相关操作
            Toast toast = Toast.makeText(getApplicationContext(), val, Toast.LENGTH_SHORT);
            toast.show();
        }
    };

    /**
     * 网络操作相关的子线程
     */
    Runnable networkTask = new Runnable() {
        @Override
        public void run() {
            // 在这里进行 http request.网络请求相关操作
            String message = "晨阳在哭！！！\n\n" + World.dbCount + "db\n\n" + new Date().toString();

            Mail m = new Mail(getApplicationContext());
            String str = m.sendMailMy(to_1, message);
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("value", str);
            msg.setData(data);
            handler.sendMessage(msg);
            lastDate = new Date();
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_test:
                new Thread(networkTask).start();
                break;
            case R.id.swh_listen:
                Switch s = (Switch) findViewById(R.id.swh_listen);
                if(s.isChecked())
                {
                    EditText e = (EditText) findViewById(R.id.email);
                    to_1 = e.getText().toString();
//                    onResume();
//                    startListenAudio();
                    isListen = true;
                    Toast toast = Toast.makeText(getApplicationContext(), "开始监听", Toast.LENGTH_SHORT);
                    toast.show();
                }else{
//                    mRecorder.delete();
//                    handler.removeMessages(msgWhat);
                    isListen = false;
                    Toast toast = Toast.makeText(getApplicationContext(), "结束监听", Toast.LENGTH_SHORT);
                    toast.show();
                }
                break;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (this.hasMessages(msgWhat)) {
                return;
            }
            volume = mRecorder.getMaxAmplitude();  //获取声压值
            if (volume > 0 && volume < 1000000) {
                float db = 20 * (float) (Math.log10(volume));
                World.setDbCount(db);  //将声压值转为分贝值
                //刷新UI界面
                if (activeStats) soundDiscView.refresh();

                if (lastDate != null && isListen) {
                    long s = ((new Date()).getTime() - lastDate.getTime()) / 1000;
                    if (World.dbCount > setting[0] && s >= padding[0]) {
                        new Thread(networkTask).start();
                        lastDate = new Date();
                    } else if (World.dbCount > setting[1] && s >= padding[1]) {
                        new Thread(networkTask).start();
                        lastDate = new Date();
                    }else if (World.dbCount > setting[2] && s >= padding[2]) {
                        new Thread(networkTask).start();
                        lastDate = new Date();
                    }

                }
            }
            handler.sendEmptyMessageDelayed(msgWhat, refreshTime);
        }
    };

    private void startListenAudio() {
        handler.sendEmptyMessageDelayed(msgWhat, refreshTime);
        Switch swi = (Switch) findViewById(R.id.swh_listen);
        if(!swi.isChecked()) swi.setChecked(true);
    }

    /**
     * 开始记录
     *
     * @param fFile
     */
    public void startRecord(File fFile) {
        try {
            mRecorder.setMyRecAudioFile(fFile);
            if (mRecorder.startRecorder()) {
                startListenAudio();
            } else {
                Toast.makeText(this, "启动录音失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "录音机已被占用或录音权限被禁止", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        mRecorder.delete();
        soundDiscView = (SoundDiscView) findViewById(R.id.soundDiscView);
        File file = FileUtil.createFile("temp.amr");
        if (file != null) {
            Log.v("file", "file =" + file.getAbsolutePath());
            startRecord(file);
        } else {
            Toast.makeText(getApplicationContext(), "创建文件失败", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 停止记录
     */
    @Override
    protected void onPause() {
        super.onPause();
//        mRecorder.delete(); //停止记录并删除录音文件
//        handler.removeMessages(msgWhat);
    }

    @Override
    protected void onDestroy() {
        wakeLock.release();
        handler.removeMessages(msgWhat);
        mRecorder.delete();
        super.onDestroy();
    }


    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if(parent==(Spinner)findViewById(R.id.spinner_setting)){
            switch (position){
                case 0:
                    setting  = setting_Higth;
                    break;
                case 1:
                    setting  = setting_normal;
                    break;
                case 2:
                    setting = setting_low;
                    break;
            }
        }
        if(parent==(Spinner)findViewById(R.id.spinner_padding)){
            switch (position){
                case 0:
                    padding  = padding_Higth;
                    break;
                case 1:
                    padding  = padding_normal;
                    break;
                case 2:
                    padding  = padding_low;
                    break;
            }
        }
        Toast toast = Toast.makeText(getApplicationContext(), "设置成功", Toast.LENGTH_SHORT);
        toast.show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
//    Activity在锁屏和开启屏幕的时候执行的方法和顺序是
//    onPause--->onStop--->onRestart--->onStart--->onResume
}
